﻿using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System;

namespace OpenWaves.Showcase.Web
{
    [DefaultImplementation(typeof(ShowcaseItemsProvider))]
    interface IShowcaseItemsProvider
    {
        IEnumerable<ShowcaseItem> ShowcaseItems { get; }
    }
    
    class ShowcaseItemsProvider: IShowcaseItemsProvider
    {        
        public IEnumerable<ShowcaseItem> ShowcaseItems
        {
            get
            {
                var showcasesFolder = this.ShowcasesFolder;

                if (!Directory.Exists(HttpContext.Current.Server.MapPath(showcasesFolder)))
                    return Enumerable.Empty<ShowcaseItem>();                               

                return Directory.GetFiles(HttpContext.Current.Server.MapPath(showcasesFolder), "*.aspx", SearchOption.AllDirectories).
                    Select(x => new ShowcaseItem()
                        {
                            Title = Path.GetFileNameWithoutExtension(x).SplitCamelCase(),
                            Identifier = Path.GetFileNameWithoutExtension(x),
                            ExampleUrl = Path.GetFullPath(x).Replace(HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty).Replace(@"\", @"/"),
                            Markup = File.ReadAllText(x).Trim(),
                            CodeBehind = File.ReadAllText(Path.ChangeExtension(x, "aspx.cs"))
                        }
                    );
            }
        }

        private string ShowcasesFolder
        {
            get
            {
                var showcasesContainer = ConfigurationManager.AppSettings["ShowcasesContainer"];
                return showcasesContainer ?? "Examples";
            }
        }
    }
}